﻿@using WebEditor.Models
@model Editor
           
@section scripts {
    <script src="@Url.Content("~/Scripts/GameEdit.js?c=" + Model.CacheBuster.ToString())" type="text/javascript"></script>
}

<div id="loading">
    <div id="loading-text">Loading...</div>
</div>

<script type="text/javascript">
    var _selectTab = "";
    var _unsavedChanges = false;

    $(function () {
        initialiseButtons();
        var layout = $('body').layout({
            applyDefaultStyles: true,
            north__resizable: false,
            north__closable: false,
            north__spacing_open: 0,
            enableCursorHotkey: false
        });
        initialiseDialogBoxes();
        window.onbeforeunload = function () {
            if (_unsavedChanges) {
                return "You have unsaved changes.";
            }
        };
        $.get('@Url.Action("Load", new { id = Model.GameId, simpleMode = Model.SimpleMode })', function (data) {
            if (data["error"]) {
                $("#dialog-error-message").html("<b>Failed to load game</b><br/><br/>" + data["error"]);
                $("#dialog-error").dialog("open");
                $("#dialog-error").data("dialog_close", function () {
                    window.location = "@Model.ErrorRedirect";
                });
            }
            else {
                if (data["editorstyle"] == "textadventure") {
                    $("#button-addpage").hide();
                }
                else if (data["editorstyle"] == "gamebook") {
                    $("#buttonset-add").hide();
                }
                initialiseTree(data["tree"], "game");
                $.get('@Url.Action("Scripts", new { id = Model.GameId })', function (data) {
                    var tabHeaderHtml = "<ul>";
                    var scriptAdderHtml = "";
                    var count = 0;
                    for (var cat in data) {
                        var divId = "cat-" + cat.replace(/ /g, "");
                        tabHeaderHtml += "<li data-key=\"" + cat + "\"><a href=\"#" + divId + "\">" + cat + "</a></li>";
                        scriptAdderHtml += "<div id=\"" + divId + "\">";
                        var scripts = data[cat].items;
                        for (var idx in scripts) {
                            var script = scripts[idx];
                            var create = script.create == null ? null : script.create.replace(/\"/g, "&quot;");
                            var additionalAttributes = (count == 0) ? " checked=\"checked\"" : "";
                            scriptAdderHtml += "<input type=\"radio\" class=\"dialog-add-script-selection\" data-key=\"" + script.key + "\" name=\"dialog-add-script-selection\" value=\"" + create + "\" id=\"dialog-add-script-selection-" + count + "\"" + additionalAttributes + "/> ";
                            scriptAdderHtml += "<label class=\"dialog-add-script-selection\" data-key=\"" + script.key + "\" for=\"dialog-add-script-selection-" + count + "\">" + script.display + "</label>";
                            scriptAdderHtml += "<br class=\"dialog-add-script-selection\" data-key=\"" + script.key + "\" />";
                            
                            if (script.button) {
                                $("<button/>", {
                                    text: script.button,
                                    "data-create": script.create,
                                    type: "button",
                                }).button().click(function () {
                                    $("#dialog-add-script").dialog("close");
                                    var key = $("#dialog-add-script").data("key");
                                    sendAdditionalAction("script add " + key + ";" + $(this).data("create"));
                                }).appendTo("#dialog-add-script-buttons");
                            }

                            count++;
                        }
                        scriptAdderHtml += "</div>";
                    }
                    tabHeaderHtml += "</ul>";
                    $("#dialog-add-script-tabs").html(tabHeaderHtml + scriptAdderHtml);
                    $("#dialog-add-script-tabs").tabs();
                });
            }
        });
        setInterval(keepSessionAlive, 60000);
        $("#button-play").attr("data-url", "@Model.PlayURL");
    });

    function keepSessionAlive() {
        $.post("/KeepAlive.ashx");
    }

    function toplevelAdditionalAction(action) {
        $("#_additionalAction").val(action);
        submitForm();
    }

    function submitForm() {
        //deinitialiseElementEditor();
        $("#elementEditorSave").submit();
    }

    function initialiseTree(data, selectElement) {
        $("#gameTree").jstree({
            plugins: ["themes", "ui", "json_data"],
            json_data: data,
            animation: 0,
            themes: {
                theme: "default",
                icons: false
            },
            ui: {
                select_limit: 1
            }
        }).bind("select_node.jstree", function (event, data) {
            if ($("#treePane").height() < data.rslt.obj.offset().top) {
                $("#treePane").animate({ scrollTop: data.rslt.obj.offset().top }, 0);
            }
            if ($("#elementEditorSave").length > 0) {
                // save current element editor first
                $("#_redirectToElement").val(data.rslt.obj.data("key"));
                submitForm();
            }
            else {
                $("#elementEditor").load('@Html.Raw(@Url.Action("EditElement", new { id = Model.GameId, key = "KEY", tab = "TAB" }))'.replace("KEY", data.rslt.obj.attr("data-key").replace(/ /g, "%20")).replace("TAB", _selectTab), function () {
                    _selectTab = "";
                    initialiseElementEditor();
                    $("#loading").hide();
                });
            }
        }).delegate("a", "click", function (event, data) { event.preventDefault(); })
            .bind("loaded.jstree", function (e, data) {
                data.inst.open_all(-1);
                data.inst.close_node("#tree-_advanced");
                selectTreeNode(selectElement);
            });
    }

    function refreshTree(selectElement, selectTab) {
        _selectTab = selectTab;
        $.get('@Url.Action("RefreshTree", new { id = Model.GameId })', function (data) {
            initialiseTree(data, selectElement);
        });
    }
</script>

<script type="text/javascript">
    var uvOptions = {};
    (function () {
        var uv = document.createElement('script'); uv.type = 'text/javascript'; uv.async = true;
        uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/ZTHBr1Zl6MlbxdyH5fFKGw.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(uv, s);
    })();
</script>

<div class="ui-layout-north">
    <div style="float: right">
        <button type="button" id="button-help">Help</button>
        <button type="button" id="button-settings">Settings</button>
        <button type="button" id="button-save" style="width: 6em">Save</button>
    </div>
    <span id="buttonset-add">
        <button type="button" id="button-addroom">Room</button>
        <button type="button" id="button-addobject">Object</button>
    </span>
    <button type="button" id="button-addpage">Page</button>
    <span id="buttonset-undoredo">
        <button type="button" id="button-undo">Undo</button>
        <button type="button" id="button-redo">Redo</button>
    </span>
    <span id="buttonset-clipboard">
        @*<button type="button" id="button-cut">Cut</button>*@
        <button type="button" id="button-copy">Copy</button>
        <button type="button" id="button-paste">Paste</button>
    </span>
    <button type="button" id="button-play">Play</button>
</div>

<div class="ui-layout-west" id="treePane">
    <div id="gameTree">
        <div id="treeContent">
        Loading...
        </div>
    </div>
</div>

<div class="ui-layout-center" id="centerPane">
    <div id="elementEditor"></div>
</div>

<div id="dialog-input-text" title="Quest">
    <p id="dialog-input-text-prompt"></p>
    <input type="text" id="dialog-input-text-entry" style="width: 100%" />
    <div id="dialog-input-text-list">
        <span id="dialog-input-text-list-prompt"></span>
        <select id="dialog-input-text-options">
        </select>
    </div>
</div>

<div id="dialog-add-script" title="Add New Script">
    <form id="dialog-add-script-form" action="">
        <div id="dialog-add-script-buttons">
        </div>
        <div id="dialog-add-script-tabs">
        </div>
    </form>
</div>

<div id="dialog-error" title="Error">
    <p id="dialog-error-message"></p>
</div>

<div id="dialog-settings" title="Settings">
    @using (Html.BeginForm("SaveSettings", "Edit", FormMethod.Post, new { id = "settings-form" }))
    {
        @Html.HiddenFor(m => m.GameId)
        @Html.CheckBoxFor(m => m.SimpleMode)
        @Html.LabelFor(m => m.SimpleMode, "Simple mode")
    }
</div>

<div id="dialog-imgPreview" title="Image Preview">
    <img id="imgPreviewElem" src="" />
</div>

<div id="dialog-upload" title="Upload File">
    <iframe src="@Url.Action("FileUpload", new { id = Model.GameId })" frameborder="0" allowtransparency="true" width="300" height="300" scrolling="no"></iframe>
</div>

<div id="dialog-codeview" title="Code View">
    <textarea id="dialog-codeview-code"></textarea>
</div>